package com.xuecheng.media.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 */
@Configuration
public class ExecutorConfig {
    /**
     * 定义线程池
     * @return
     */
    @Bean(name="taskExecutor")
    public Executor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);    //设置核心线程数
        executor.setMaxPoolSize(5);     //设置最大线程数
        executor.setThreadNamePrefix("media-executor-");    //指定线程名前缀
        executor.setQueueCapacity(90); //指定队列容量
        //拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        //关键配置，优雅关闭参数
        //这个是设置当前城池关闭时，等待队列的任务执行完毕再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //这个是最多等待30秒，防止无限等待
        executor.setAwaitTerminationSeconds(30);
        executor.initialize();
        return executor;
    }
}
